<template>
  <n-modal
    v-model:show="showModal"
    :show-icon="false"
    preset="dialog"
    :title="title"
    :style="{ width: props.width + 'px' }"
    @update:show="handleUpdateShow"
  >
    <n-spin :show="modalLoading" content-class="max-h-[80vh] overflow-auto pr-2">
      <n-form :model="formData" :rules="formRules" ref="formRef" label-width="auto" label-placement="top">
        <n-grid :cols="1" :x-gap="24">
          <n-form-item-gi label="路由" path="routeId">
            <n-tree-select
              :options="routeDataOpts"
              key-field="routeId"
              label-field="routeNm"
              placeholder="请输入路由编号"
              v-model:value="formData.routeId"
            />
          </n-form-item-gi>
          <n-form-item-gi label="权限名称" path="permNm">
            <n-input placeholder="请输入权限名称" v-model:value="formData.permNm" />
          </n-form-item-gi>
          <n-form-item-gi label="权限标签" path="permLbl">
            <n-input placeholder="请输入权限标签" v-model:value="formData.permLbl" />
          </n-form-item-gi>
          <n-form-item-gi label="权限描述" path="permDsc">
            <n-input placeholder="请输入权限描述" v-model:value="formData.permDsc" type="textarea" :autosize="{ minRows: 3, maxRows: 5 }" />
          </n-form-item-gi>
          <n-form-item-gi label="排序号" path="ordrNum">
            <n-input-number placeholder="请输入排序号" v-model:value="formData.ordrNum" />
          </n-form-item-gi>
          <n-form-item-gi label="备注" path="rmrk">
            <n-input placeholder="请输入备注" v-model:value="formData.rmrk" type="textarea" :autosize="{ minRows: 3, maxRows: 5 }" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </n-spin>
    <template #action>
      <n-space>
        <n-button @click="() => handleUpdateShow(false)">取消</n-button>
        <n-button v-if="hasPermission('bmpch:route:tree:perm:save', '保存路由权限')" type="info" :loading="saveBtnLoading" @click="handleSave">
          <template #icon>
            <n-icon>
              <SaveOutlined />
            </n-icon>
          </template>
          保存
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import { reactive, ref, unref, watch } from 'vue';
import type { FormRules, FormInst } from 'naive-ui';
import { SaveOutlined } from '@vicons/antd';
import type * as BMPCH from '@yanfan/bmpch-tsapi/types';
import { routeQry001, routePermGet, routePermSav } from '@yanfan/bmpch-tsapi/route';
import { usePermission } from '@yanfan/common/hooks';

defineOptions({
  name: 'BmpchRoutePermEdit',
  titl: '路由权限编辑',
});

const { hasPermission } = usePermission();

const props = withDefaults(
  defineProps<{
    show: boolean;
    width?: number;
    bizId: string | null;
    routeId: string | null;
  }>(),
  {
    show: false,
    width: 530,
  },
);

const emits = defineEmits<{
  (e: 'update:show', show: boolean): void;
  (e: 'refresh'): void;
}>();

class FormData {
  permId: string = '';
  permNm: string = '';
  permLbl: string = '';
  permDsc: string = '';
  routeId: string = '';
  chnlId: string = '';
  rmrk: string = '';
  delFlg: number = 0;
  ordrNum: number = 0;
}

const formRules: FormRules = {
  permNm: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入权限名称',
  },
  permLbl: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入权限标签',
  },
  routeId: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入路由编号',
  },
  chnlId: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入渠道编号',
  },
};

const title = ref('新建');
const modalLoading = ref(false);
const formRef = ref<FormInst | null>(null);
const showModal = ref(false);
const saveBtnLoading = ref(false);
const formData = reactive(new FormData());
const routeDataOpts = ref<BMPCH.RouteQry001Output_RouteDto[]>([]);

watch(
  () => unref(props).show,
  (show) => {
    showModal.value = show;
    if (showModal.value) {
      loadRouteData();
      if (props.bizId) {
        title.value = '编辑';
        modalLoading.value = true;
        routePermGet({ permId: props.bizId })
          .then((data: BMPCH.RoutePermGetOutput) => {
            Object.assign(formData, data);
          })
          .finally(() => {
            modalLoading.value = false;
          });
      } else {
        title.value = '新建';
        Object.assign(formData, new FormData());
      }
    } else {
      Object.assign(formData, new FormData());
    }
  },
);

function handleUpdateShow(value: boolean) {
  emits('update:show', value);
}

function handleSave() {
  saveBtnLoading.value = true;
  formRef.value
    ?.validate()
    .then(() => {
      routePermSav(formData).then((data: BMPCH.RoutePermSavOutput) => {
        if (data.success) {
          formData.permId = data.permId;
          handleUpdateShow(false);
          window.$message.success('保存成功');
          emits('refresh');
        } else {
          window.$message.error(data.errmsg);
        }
      });
    })
    .catch(() => {
      window.$message.error('请填写完整信息');
    })
    .finally(() => {
      saveBtnLoading.value = false;
    });
}

function loadRouteData() {
  routeQry001({}).then((data) => {
    routeDataOpts.value = data.list;
    handleLeafNode(null, routeDataOpts.value);
  });
}

function handleLeafNode(parent: BMPCH.RouteQry001Output_RouteDto | null, nodes: Array<any>) {
  nodes.map((node) => {
    node.parent = parent;
    if (node.children && node.children.length === 0) {
      node.isLeaf = true;
    } else {
      handleLeafNode(node, node.children);
    }
  });
}
</script>

<style lang="less" scoped></style>
